package com.herench.bs.transfer;

import com.herench.bs.transfer.Dialect;
import com.herench.bs.utils.DataFormatUtils;
import org.apache.cxf.endpoint.Client;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.*;

/**
 * cleverClinic
 * com.herench.bs.transfer.transfer
 *
 * @author wangwenkai
 * @date 2017/11/25/17:20
 */
public class LoadClinicOrderDetailsTransfer extends AbstractTransfer {

    public LoadClinicOrderDetailsTransfer(String method, Client client,String messageMethod) {
        super(method, client,messageMethod);
    }

    private String paySeq;


    @Override
    public String toInvokeMessage(Map<String, Object> params) throws Exception {
        this.paySeq = (String) params.get("paySeq");
        String idCard = (String) params.get("idCard");
        String patientId = (String) params.get("patientId");
        String appointDate = DataFormatUtils.getSimpleTimeString((Date) params.get("appointDate"));
        String tranNo = (String) params.get("tranNo");
        String visitNo = (String) params.get("visitNo");
        Document tplDoc = getTplDoc(getMethod());
        Element dataRowElement = tplDoc.getRootElement().element("CommitData").addElement("Data").addElement("DataRow");
//        dataRowElement.addAttribute("PATIENT_ID", patientId).addAttribute("START_DATE", appointDate).addAttribute("END_DATE", appointDate);
        dataRowElement.addAttribute("PERSON_NO", idCard).addAttribute("PATIENT_ID", patientId).addAttribute("VISIT_NO", visitNo).addAttribute("VISIT_DATE", appointDate).addAttribute("TRAN_NO", tranNo);
        return tplDoc.asXML();
    }

    @Override
    public Map<String, Object> toResultMessage(String resMsg) throws Exception {
        Map<String, Object> res = new HashMap<>(16);
        Document document = DocumentHelper.parseText(resMsg);
        Element resultInfo = document.getRootElement().element("Result").element("Info");
        String executeStatus = resultInfo.attributeValue("EXECUTE_STATUS");
        String executeMessage = resultInfo.attributeValue("EXECUTE_MESSAGE");
        double totalCost = 0;
        List<Map<String, Object>> chargeDetailsList = new ArrayList<>();
        if (Dialect.getSuccessfulState().equals(executeStatus)) {
            List<Element> dataRow = document.getRootElement().element("ReturnData").element("Data").elements();
            Map<String, Object> detailsMap = new HashMap<>(16);
            for (Element element : dataRow) {
                LoadClinicChargeOrderInnerMessage innerMassaage = new LoadClinicChargeOrderInnerMessage(element);
                if (this.paySeq.equals(innerMassaage.getAppNo())) {
                    String subTotalCost = innerMassaage.getCharges();
                    totalCost = totalCost + Double.parseDouble(subTotalCost);
                    Map<String, Object> subCostTypeMap = (Map<String, Object>) detailsMap.get(innerMassaage.getReqClass());
                    if (subCostTypeMap == null) {
                        subCostTypeMap = new HashMap<>(16);
                        detailsMap.put(innerMassaage.getReqClass(), subCostTypeMap);
                        subCostTypeMap.put("subCostTypeName", innerMassaage.getReqClass());
                    }
                    String subCost = (String) subCostTypeMap.get("subCost");
                    if(innerMassaage.getReqClass().equals("检查")||innerMassaage.getReqClass().equals("检验")||innerMassaage.getReqClass().equals("其他")){
                        if(innerMassaage.getAffirStatus().equals("1")){
                            subCostTypeMap.put("statusName","已执行");
                        }else {
                            subCostTypeMap.put("statusName","未执行");
                        }
                    }
                    if(innerMassaage.getReqClass().equals("处方")){
                        if(innerMassaage.getAffirStatus().equals("1")){
                            subCostTypeMap.put("statusName","已取药");
                        }else {
                            subCostTypeMap.put("statusName","未取药");
                        }
                    }
                    if (subCost == null) {
                        subCost = innerMassaage.getCharges();
                        subCostTypeMap.put("subCost", subCost);
                    } else {
                        double subCostDouble = Double.parseDouble(subCost);
                        double innerSubCostDouble = Double.parseDouble(innerMassaage.getCharges());
                        double sum = subCostDouble + innerSubCostDouble;
                        subCostTypeMap.put("subCost", DataFormatUtils.getFormatMoney(sum));
                    }
                    List<Map<String, Object>> costList = (List<Map<String, Object>>) subCostTypeMap.get("costList");
                    if (costList == null) {
                        costList = new ArrayList<>();
                        subCostTypeMap.put("costList", costList);
                    }
                    Map<String, Object> el = new HashMap<>(16);
                    el.put("clinicCostItemNo", innerMassaage.getClinicCostItemNo());
                    el.put("itemCode", innerMassaage.getItemCode());
                    el.put("itemName", innerMassaage.getItemName());
                    el.put("itemSpec", innerMassaage.getItemSpec());
                    el.put("amount", innerMassaage.getAmount());
                    el.put("units", innerMassaage.getUnits());
                    el.put("orderedBy", innerMassaage.getOrderedBy());
                    el.put("orderedDoctor", innerMassaage.getOrderedDoctor());
                    el.put("charges", innerMassaage.getCharges());
                    el.put("inputDateTime", innerMassaage.getInputDateTime().replace('/','-'));
                    el.put("reqId", innerMassaage.getReqId());
                    el.put("usage", innerMassaage.getAdmin());
                    el.put("docName", innerMassaage.getOrderedDoctor());
                    el.put("clinicId", innerMassaage.getClinicId());
                    el.put("performedBy", innerMassaage.getPerformedBy());
                    el.put("deptName", innerMassaage.getPerformedByName());
                    el.put("parentName", "");
                    el.put("docInsurType", "");
                    el.put("status",innerMassaage.getStatus());
                    el.put("affirStatus",innerMassaage.getAffirStatus());
                    if(innerMassaage.getReqClass().equals("检查")||innerMassaage.getReqClass().equals("检验")||innerMassaage.getReqClass().equals("其他")){
                        if(innerMassaage.getAffirStatus().equals("1")){
                            el.put("statusName","已执行");
                        }else {
                            el.put("statusName","未执行");
                        }
                    }
                    if(innerMassaage.getReqClass().equals("处方")){
                        if(innerMassaage.getAffirStatus().equals("1")){
                            el.put("statusName","已取药");
                        }else {
                            el.put("statusName","未取药");
                        }
                    }
                    costList.add(el);
                }
            }
            for (Map.Entry<String, Object> entry : detailsMap.entrySet()) {
                Map<String, Object> subCostTypeMap = (Map<String, Object>) entry.getValue();
                List<Map<String, Object>> costList = (List<Map<String, Object>>) subCostTypeMap.get("costList");
                if (costList != null) {
                    LoadClinicChargeOrderInnerMessage innerMassaage = new LoadClinicChargeOrderInnerMessage(dataRow.get(0));
                    Map<String, Object> elMap = new LinkedHashMap<>();
                    elMap.put("subCostTypeName", entry.getKey());
                    elMap.put("subCostTypeCode", Dialect.getSubCostTypeCode(entry.getKey()));
                    elMap.put("subCost", subCostTypeMap.get("subCost"));
                    elMap.put("costList", costList);
//                    if(entry.getKey().equals("检查")||entry.getKey().equals("检验")||entry.getKey().equals("其他")){
//                        if(innerMassaage.getAffirStatus().equals("1")&&this.paySeq.equals(innerMassaage.getAppNo())){
//                            elMap.put("statusName","已执行");
//                        }else {
//                            elMap.put("statusName","未执行");
//                        }
//                    }
//                    if(entry.getKey().equals("处方")){
//                        if(innerMassaage.getAffirStatus().equals("1")&&this.paySeq.equals(innerMassaage.getAppNo())){
//                            elMap.put("statusName","已取药");
//                        }else {
//                            elMap.put("statusName","未取药");
//                        }
//                    }
                    elMap.put("statusName",((Map<String, Object>) entry.getValue()).get("statusName"));
                    elMap.put("performedByName",costList.get(0).get("deptName"));
                    chargeDetailsList.add(elMap);
                    subCostTypeMap.remove("subCost");
                }
            }
            res.put("chargeDetailsList", chargeDetailsList);
            if (chargeDetailsList.size() == 0 || chargeDetailsList == null) {
                res.put("totalCost", "0.00");
                res.put("code", "1");
                res.put("message", "未查询到开单记录详情！");
            } else {
                res.put("totalCost", DataFormatUtils.getFormatMoney(totalCost));
                res.put("code", executeStatus);
                res.put("message", executeMessage);
            }
        } else {
            res.put("code", executeStatus);
            res.put("message", executeMessage);
        }

        return res;
    }

    public class LoadClinicChargeOrderInnerMessage implements InnerMessage {
        /**
         * 开单项目序号
         */
        private String clinicCostItemNo;
        /**
         * 患者ID
         */
        private String patientId;
        /**
         * 项目编码
         */
        private String itemCode;
        /**
         * 项目名称
         */
        private String itemName;
        /**
         * 项目规格
         */
        private String itemSpec;
        /**
         * 数量
         */
        private String amount;
        /**
         * 单位
         */
        private String units;
        /**
         * 开单科室代码
         */
        private String orderedBy;
        /**
         * 开单医师姓名
         */
        private String orderedDoctor;
        /**
         * 应收费用
         */
        private String costs;
        /**
         * 实收费用
         */
        private String charges;
        /**
         * 医嘱开立时间
         */
        private String inputDateTime;
        /**
         * 开单类别
         */
        private String reqClass;
        /**
         * 开单识别号
         */
        private String reqId;
        /**
         * 用法
         */
        private String admin;
        /**
         * 处方号
         */
        private String appNo;
        /**
         * 就诊ID，就诊日期YYYYMMDD+就诊号
         */
        private String clinicId;
        /**
         * 执行科室代码
         */
        private String performedBy;
        /**
         * 收费状态
         */
        private String status;
        /**
         * 统筹支付
         */
        private String insurPay;
        /**
         * 个人账户支付
         */
        private String accountPay;
        /**
         * 个人自费
         */
        private String ownPay;
        /**
         * 开单科室名称
         */
        private String orderedByName;
        /**
         * 执行科室名称
         */
        private String performedByName;
        /**
         * 取药窗口号
         */
        private String drugWinNo;
        /**
         * 执行状态
         */
        private String affirStatus;


        public String getClinicCostItemNo() {
            return clinicCostItemNo;
        }

        public String getPatientId() {
            return patientId;
        }

        public String getItemCode() {
            return itemCode;
        }

        public String getItemName() {
            return itemName;
        }

        public String getItemSpec() {
            return itemSpec;
        }

        public String getAmount() {
            return amount;
        }

        public String getUnits() {
            return units;
        }

        public String getOrderedBy() {
            return orderedBy;
        }

        public String getOrderedDoctor() {
            return orderedDoctor;
        }

        public String getCosts() {
            return costs;
        }

        public String getCharges() {
            return charges;
        }

        public String getInputDateTime() {
            return inputDateTime;
        }

        public String getReqClass() {
            return reqClass;
        }

        public String getReqId() {
            return reqId;
        }

        public String getAdmin() {
            return admin;
        }

        public String getAppNo() {
            return appNo;
        }

        public String getClinicId() {
            return clinicId;
        }

        public String getPerformedBy() {
            return performedBy;
        }

        public String getStatus() {
            return status;
        }

        public String getInsurPay() {
            return insurPay;
        }

        public String getAccountPay() {
            return accountPay;
        }

        public String getOwnPay() {
            return ownPay;
        }

        public String getOrderedByName() {
            return orderedByName;
        }

        public String getPerformedByName() {
            return performedByName;
        }

        public String getDrugWinNo() {
            return drugWinNo;
        }

        public String getAffirStatus() {
            return affirStatus;
        }

        public LoadClinicChargeOrderInnerMessage(Element element) {
            this.clinicCostItemNo = element.attributeValue("CLINIC_COST_ITEM_NO");
            this.patientId = element.attributeValue("PATIENT_ID");
            this.itemCode = element.attributeValue("ITEM_CODE");
            this.itemName = element.attributeValue("ITEM_NAME");
            this.itemSpec = element.attributeValue("ITEM_SPEC");
            this.amount = element.attributeValue("AMOUNT");
            this.units = element.attributeValue("UNITS");
            this.orderedBy = element.attributeValue("ORDERED_BY");
            this.orderedDoctor = element.attributeValue("ORDERED_DOCTOR");
            this.costs = element.attributeValue("COSTS");
            this.charges = element.attributeValue("CHARGES");
            this.inputDateTime = element.attributeValue("INPUT_DATE_TIME");
            this.reqClass = element.attributeValue("REQ_CLASS");
            this.reqId = element.attributeValue("REQ_ID");
            this.admin = element.attributeValue("ADMIN");
            this.appNo = element.attributeValue("APP_NO");
            this.clinicId = element.attributeValue("CLINIC_ID");
            this.performedBy = element.attributeValue("PERFORMED_BY");
            this.status = element.attributeValue("STATUS");
            this.insurPay = element.attributeValue("INSUR_PAY");
            this.accountPay = element.attributeValue("ACCOUNT_PAY");
            this.ownPay = element.attributeValue("OWN_PAY");
            this.orderedByName = element.attributeValue("ORDERED_BY_NAME");
            this.performedByName = element.attributeValue("PERFORMED_BY_NAME");
            this.drugWinNo = element.attributeValue("DRUG_WIN_NO");
            this.affirStatus = element.attributeValue("AFFIR_STATUS");
        }
    }
}
